#include "StdAfx.h"
#include "HttpHelper.h"

bool CHttpHelper::GetRandCode(const RequestInfo& reqInfo, ResponseInfo& respInfo, const wstring& pngPath)
{
	if (!SendHttpRequest(reqInfo, respInfo))
	{
		return false;
	}

	return CFileHelper::SetFileBuf(pngPath, (B5M_UINT8*)respInfo.m_rawData.c_str(), respInfo.m_rawData.length());;
}

bool CHttpHelper::SendHttpRequest(const RequestInfo& reqInfo, ResponseInfo& respInfo)
{
	WinHttpClient http(reqInfo.m_url);

	// header
	if (!reqInfo.m_header.empty())
	{
		if (!http.SetAdditionalRequestHeaders(reqInfo.m_header))
		{
			DEBUGW(DBG_ERROR, L"http.SetAdditionalRequestHeaders FAILED. GetLastError: " << GetLastError());
			return false;
		}
	}

	// set post data
	if (HTTP_POST == reqInfo.m_type)
	{
		string tmpBody = CStringHelper::Unicode2UTF8(reqInfo.m_body);
		if (!http.SetAdditionalDataToSend((BYTE*)(tmpBody.c_str()), tmpBody.length()))
		{
			DEBUGW(DBG_ERROR, L"http.SetAdditionalDataToSend FAILED. GetLastError: " << GetLastError());
			return false;
		}
	}

	// send http request
	if (!http.SendHttpRequest(reqInfo.m_type))
	{
		DEBUGW(DBG_ERROR, L"http.SendHttpRequest FAILED. GetLastError: " << GetLastError());
		return false;
	}

	if (L"200" != http.GetResponseStatusCode())
	{
		DEBUGW(DBG_ERROR, L"SendHttpRequest FAILED. GetResponseStatusCode: " << http.GetResponseStatusCode());
		return false;
	}

	respInfo.m_header = http.GetResponseHeader();
	respInfo.m_content = http.GetResponseContent();
	respInfo.m_cookie = http.GetResponseCookies();
	string rawData = string((char*)http.GetRawResponseContent(), http.GetRawResponseContentLength());
	respInfo.m_rawData = rawData;//CStringHelper::ASCII2Unicode(rawData);

	return true;
}